package com.gph.saviorframework.auth.controller;

import com.gph.saviorframework.Constants;
import com.gph.saviorframework.SaviorFrameworkException;
import com.gph.saviorframework.auth.model.AuthSystem;
import com.gph.saviorframework.auth.sec.rsa.RsaUtils;
import com.gph.saviorframework.auth.service.AuthSystemService;
import com.gph.saviorframework.util.RequestUtil;
import com.gph.saviorframework.util.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/" + Constants.FRAMEWORK_REQUEST_PATH + "/auth/sys")
public class AuthSystemController {

    /** 日志输出 */
    final Logger logger = LoggerFactory.getLogger(AuthSystemController.class);

    @Autowired
    private AuthSystemService authSystemService;

    @Autowired
    private SecurityUtils securityUtils;

    @Autowired
    private MessageSourceAccessor messages;

    private String domain = AuthSystem.class.getSimpleName().toLowerCase();

    private final String viewPrefix = Constants.FRAMEWORK_REQUEST_PATH + "/auth/sys/";

    @RequestMapping(value = "/create",method = RequestMethod.GET)
    public String sysCreatePage(){
        return viewPrefix+"sys_create";
    }

    @RequestMapping(value = "/create",method = RequestMethod.POST)
    @ResponseBody
    public ModelMap create(@ModelAttribute AuthSystem authSystem){
        ModelMap modelMap = new ModelMap();
        try{
            Date date = new Date();

            Map<String,Object> keyMap = RsaUtils.genKeyPair();
            authSystem.setId(UUID.randomUUID().toString());
            authSystem.setPublicKey(RsaUtils.getPublicKey(keyMap));
            authSystem.setPrivateKey(RsaUtils.getPrivateKey(keyMap));
            authSystem.setCreateTime(date);
            authSystem.setUpdateTime(date);

            authSystemService.save(authSystem);

            modelMap.addAttribute(Constants.DEFAULT_SUCCESS_KEY,Boolean.TRUE);
            modelMap.addAttribute(Constants.DEFAULT_ID_KEY,authSystem.getId());
        }
        catch (Exception ex){
            ex.printStackTrace();
            modelMap.addAttribute(Constants.DEFAULT_SUCCESS_KEY,Boolean.FALSE);
        }
        return modelMap;
    }

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list() throws SaviorFrameworkException {
        return viewPrefix + "list";
    }

    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ResponseBody
    public String list(
            @RequestParam(value = Constants.DEFAULT_PAGE_MODEL_KEY, required = false, defaultValue = Constants.DEFAULT_PAGE_START) Integer start,
            @RequestParam(value = Constants.DEFAULT_RECORD_MODEL_KEY, required = false, defaultValue = Constants.DEFAULT_PAGE_SIZE) Integer limit,
            @RequestParam(value = Constants.DEFAULT_SORT_MODEL_KEY, required = false, defaultValue = Constants.DEFAULT_SORT_FIELD) String sort,
            @RequestParam(value = Constants.DEFAULT_DIR_MODEL_KEY, required = false, defaultValue = Constants.DEFAULT_SORT_DIRECTION) String dir,
            HttpServletRequest request) throws SaviorFrameworkException {
        String json = null;
        Map<String, Object> params = RequestUtil.getQueryMap(request, authSystemService.getFields());
        try {
            json = com.alibaba.fastjson.JSONArray.toJSONString(authSystemService.find(start,limit,sort,dir,params));
            logger.info(messages.getMessage("log.info.list", new String[] { securityUtils.getUserFullName(), messages.getMessage(domain) }));
        }
        catch (DataAccessException e) {
            e.printStackTrace();
            logger.error(messages.getMessage("log.error.list", new String[] { securityUtils.getUserFullName(), messages.getMessage(domain) }));
        }
        return json;
    }
}
